//package com.itcoon.common.webmvc.exception.listener;
//
//
//import exception.com.itcoon.cloud.framework.ex.BaseServiceException;
//import com.itcoon.utils.cloud.IPUtil;
//import com.itcoon.utils.cloud.SpringUtils;
//import properties.config.webmvc.com.itcoon.cloud.framework.GlobalExceptionAlarmConfigProperties;
//import event.listener.exception.webmvc.com.itcoon.cloud.framework.GlobalExceptionEvent;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.event.EventListener;
//import org.springframework.core.env.Environment;
//import org.springframework.core.io.Resource;
//import org.springframework.scheduling.annotation.Async;
//import org.springframework.util.StringUtils;
//
//import java.io.IOException;
//import java.time.LocalDateTime;
//import java.time.temporal.ChronoUnit;
//import java.util.Arrays;
//import java.util.HashMap;
//import java.util.Map;
//
//public class GlobalExceptionListener {
//
//    @Autowired(required = false)
//    private EmailService emailService;
//
//    @Autowired
//    private GlobalExceptionAlarmConfigProperties properties;
//
//    @Autowired
//    private Environment environment;
//
//    private Map<String, LocalDateTime> map = new HashMap<>();
//
//
//    @Async
//    @EventListener(GlobalExceptionEvent.class)
//    public <E extends Exception> void processGlobalException(GlobalExceptionEvent<E> event){
//        GlobalExceptionAlarmConfigProperties.Alarm alarm = properties.getAlarm();
//        if(alarm.getEnable()){
//            Exception e = event.getE();
//            try {
//                if (e instanceof BaseServiceException) {
//                    BaseServiceException exception = (BaseServiceException) event.getE();
//                    if (alarm.getAlarmCodes().contains(exception.getCode())) {
//                        doSend(e.getClass().getName(), exception.getMessage(), e.getStackTrace(), alarm.getReceivers());
//                    }
//                } else {
//                    doSend(e.getClass().getName(), e.getLocalizedMessage(), e.getStackTrace(), alarm.getReceivers());
//                }
//            }catch (IOException ioe) {
//                throw new RuntimeException(ioe.getMessage(), ioe);
//            }
//        }
//    }
//
//    private void doSend(String exClassName, String errMsg, StackTraceElement[] stackTrace,  String... receivers) throws IOException {
//        String key = exClassName + "::" + errMsg;
//        LocalDateTime lastTime = map.get(key);
//        if(lastTime == null || LocalDateTime.now().isAfter(lastTime.plus(properties.getAlarm().getMinRate(), ChronoUnit.MILLIS))){
//            String templateSourcePath = properties.getAlarm().getTemplateSourcePath();
//            MailRequest.Builder builder = MailRequest.builder(StringUtils.hasText(templateSourcePath))
//                    .receivers(receivers)
//                    .subject(environment.getProperty("spring.application.name") + "日志异常告警")
//                    .addAttachment("exception.log", new ByteArrayDataSource(StringUtils.collectionToDelimitedString(Arrays.asList(stackTrace),"\n"), "application/octet-stream"));
//
//            if(StringUtils.hasText(templateSourcePath)){
//                Map<String, String> metaMap = new HashMap<>();
//                metaMap.put("host", IPUtil.getServerIP());
//                metaMap.put("exceptionClass", exClassName);
//                metaMap.put("message", errMsg);
//                metaMap.put("profile", StringUtils.collectionToDelimitedString(Arrays.asList(environment.getActiveProfiles()), ","));
//                metaMap.put("dateTime", DateTimeConverter.format(LocalDateTime.now()));
//                ApplicationContext context = SpringUtils.getContext();
//                Resource resource = context.getResource(templateSourcePath);
//                builder.content(resource, metaMap);
//            }else {
//                String content  = "Host: " + IPUtil.getServerIP() + "\r\n"
//                        + "Exception Class: " +exClassName + "\r\n"
//                        + "Message: " + errMsg + "\r\n"
//                        + "Profile: " + environment.getActiveProfiles()[0] + "\r\n"
//                        + "\r\n\r\n"
//                        + DateTimeConverter.format(LocalDateTime.now());
//                builder.content(content);
//            }
//            emailService.sendEmail(builder.build());
//            map.put(key, LocalDateTime.now());
//        }
//    }
//}
